package com.Smart.smartscals.Utils;

import com.Smart.smartscals.DataBase.DataBaseService;
import com.Smart.smartscals.Entity.EntityConversionTime;
import com.Smart.smartscals.Entity.EntityReciveBodyInfo;
import com.Smart.smartscals.Entity.EntitySaveBodyInfo;

import android.content.Context;


/**
 * �������ڸ�����ݿ���ݵ���
 * @author Administrator
 *
 */
public class UpLoadDataBaseUtils {
	private DataBaseService mDataService;
	private Context context;
	private boolean boo;
	//		if (cursor.moveToLast()) {
	//		    // ��cursor�����һ�����
	//		}
	/**
	 * ����bodyInformation�ĺ���
	 * @param bodyInfoEntity
	 * 
	 */
	public UpLoadDataBaseUtils(Context context){
		this.context = context;

	}
	public void insertBodyInfo(EntitySaveBodyInfo bodyInfoEntity){
		mDataService = DataBaseService.getInstance(context);
		long mdate = bodyInfoEntity.getDate();
		String muserName = bodyInfoEntity.getUserName();
		
		SeletLastDataBaseUtilt getLastDatebBase = new SeletLastDataBaseUtilt(context);
		EntityReciveBodyInfo lastBodyInfoEntity = getLastDatebBase.getLastBodyInfoEntity(muserName);
		
		long lastDate = lastBodyInfoEntity.getDate();
		
		//�Ѻ���ֵת��Ϊ��ݡ��·ݡ�������������
		MSConversionToValues msConversionToValues = new MSConversionToValues();
		EntityConversionTime timeEntity = msConversionToValues.mSConverTOValues(mdate);
		if(lastDate!=0){
		//�ж��ǲ���ͬһ��
		 boo = isSameDay(mdate,lastDate);
		}
		int weekNum  = timeEntity.getWeekNUM();
		int monthNum = timeEntity.getMonthNUM();
		int dayNum = timeEntity.getDayNUM();
		int yearNum = timeEntity.getYearNUM();
		float weight = bodyInfoEntity.getWeight();
		float bodyfat = bodyInfoEntity.getBodyFat();
		//�����ͬһ���ȡƽ��ֵ�ٸ������
		if(boo){
			float lastweight = lastBodyInfoEntity.getWeight();
			float lastbodyFat = lastBodyInfoEntity.getBodyFat();
		
			float currentWeight = (lastweight+weight)/2;
			float currentFat = (lastbodyFat+bodyfat)/2;
			//lastDateΪ���һ�β�ѯ��ʱ��
			mDataService.updateBodyInfo(lastDate, currentWeight, currentFat, weekNum, monthNum, dayNum, yearNum,muserName);

		}else{
			
			//����ͬһ���ֱ�Ӳ������
			mDataService.insertBodyInfo(mdate, weight, bodyfat, weekNum, monthNum, dayNum, yearNum,muserName);
		}
	}
	private	boolean isSameDay(long mdate,long lastDate) {
		String DATE_FORMAT = "yyyy-MM-dd";
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
		String mdateStr = sdf.format(mdate);
		String lastdateStr = sdf.format(lastDate);
		return mdateStr.equals(lastdateStr);
	}

}
